import 'package:flutter/material.dart';

class ScrollListen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _ScrollListenState();
  }
}

class _ScrollListenState extends State<ScrollListen> {

  ScrollController _controller = ScrollController();
  bool _showToTopBtn = false; //是否显示“返回到顶部”按钮

  @override
  void initState() {
    _controller.addListener(() {
      print(_controller.offset);
      if (_controller.offset < 800 && _showToTopBtn) {
        setState(() {
          _showToTopBtn = false;
        });
      } else if (_controller.offset >= 800 && _showToTopBtn == false) {
        setState(() {
          _showToTopBtn = true;
        });
      }
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('滚动控制'),
      ),

      body: Scrollbar(
        child: ListView.builder(
          itemBuilder: (context, index) {
            return ListTile(title: Text('第$index行'),);
          },
          itemCount: 100,
          itemExtent: 50,
          controller: _controller,
        ),
      ),

      floatingActionButton: ((){
        if (_showToTopBtn) {
          return FloatingActionButton(
            onPressed: (){
              _controller.animateTo(0, duration: Duration(milliseconds: 200), curve: Curves.ease);
            },
            child: Icon(Icons.arrow_upward),
          );
        } else {
          return null;
        }
      })(),
    );
  }
}